import axios, { AxiosInstance } from 'axios'
import { message } from 'antd'
import { useAppStore } from '@/store/appStore'
import { appConfig } from '@/config'

// 创建 axios 实例
const createAxiosInstance = (): AxiosInstance => {
  const instance = axios.create({
    baseURL: appConfig.api.baseURL,
    timeout: appConfig.api.timeout,
  })
  
  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      const token = useAppStore.getState().jwt
      if (token) {
        config.headers[appConfig.auth.tokenKey] = `Bearer ${token}`
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )
  
  // 响应拦截器
  instance.interceptors.response.use(
    (response) => {
      return response.data
    },
    (error) => {
      if (error.response?.status === 401) {
        useAppStore.getState().logOut()
        window.location.href = '/login'
        message.error('登录已过期，请重新登录')
      } else if (error.response?.status === 403) {
        window.location.href = '/error?code=403'
      } else if (error.response?.status === 404) {
        message.error('请求的资源不存在')
      } else if (error.response?.status >= 500) {
        // 服务器错误，可选择是否跳转到错误页面
        message.error('服务器错误，请稍后重试')
        // 如果需要跳转到 500 页面，取消下面的注释
        // window.location.href = '/500'
      } else {
        message.error(error.response?.data?.message || '请求失败')
      }
      return Promise.reject(error)
    }
  )
  
  return instance
}

export const axiosInstance = createAxiosInstance()